<template>
  <div class="main">
    <el-card style="max-width: 50%">
      <template #header>
        <div class="card-header">
          <span>用户修改账号</span>
        </div>
      </template>
      <el-form
        label-width="auto"
        style="max-width: 600px"
        :model="form"
        ref="forms"
        :rules="rules"
      >
        <el-form-item label="用户名">
          <el-input :value="useStore.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="新邮箱" prop="new_email">
          <el-input v-model="form.new_email" />
        </el-form-item>
        <div class="center">
          <el-button type="primary" @click="submit">确认修改</el-button>
          <el-button
            type="primary"
            plain
            size="small"
            :icon="Refresh"
            @click="fresh"
          ></el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
// 引入用户小仓库
import useUserStore from '@/store/modules/user'
// 引入接口
import { reqAccount } from '@/api/user/index'
import { ElNotification } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const useStore = useUserStore() // 创建用户实例

const form = reactive({
  email: '',
  new_email: '',
})
// 获取el-form组件
const forms = ref()
// 刷新
const fresh = () => {
  location.reload()
}
// 确认修改
const submit = async () => {
  // 保证全部表单校验通过之后再发请求
  await forms.value.validate()
  let res = await reqAccount(useStore.userId, form)
  if (res.code === 200) {
    ElNotification({
      message: res.msg,
      type: 'success',
    })
    // 点击过后刷新
    location.reload()
  } else {
    ElNotification({
      message: res.error_msg,
      type: 'error',
    })
  }
}
//自定义校验规则函数
const validatorEmail = (rule: any, value: any, callback: any) => {
  let regExp = /^[a-zA-Z0-9]{9,11}@(qq\.com|163\.com)$/
  if (value === '') {
    callback(new Error('邮箱不能为空！'))
  } else if (regExp.test(value)) {
    callback()
  } else {
    callback(
      new Error('请输入符合要求的邮箱，例如：xxxx@qq.com 或 xxxx@163.com'),
    )
  }
}
const validatorNewEmail = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('邮箱不能为空！'))
  } else if (value === form.email) {
    callback(new Error('两次输入的邮箱不能一致!'))
  } else {
    callback()
  }
}
//定义表单校验需要配置对象
const rules = {
  email: [{ trigger: 'change', validator: validatorEmail }],
  new_email: [{ trigger: 'change', validator: validatorNewEmail }],
}
</script>

<style lang="scss" scoped>
.main {
  .card-header {
    text-align: center;
    font-size: 25px;
  }
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
